package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.msg.SeckillGoodCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scripting.bsh.BshScriptUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Override
    @Transactional
    public String doSeckill(Long Uid, Long seckillId) {
        // 6.1减真实库存
        //count==0就是影响行=0：库存不足
        int count = seckillGoodService.decr(seckillId);

        if (count==0){
           throw new BusinessException(SeckillGoodCodeMsg.NO_STOCKCOUNT);
        }
// 6.2创建出来订单信息保存到数据库中
       String orderNo =createOrderInfo(Uid,seckillId);
// 6.3往tseckilL_order去存储一条数据，作为这个用户已经下单的依据
        //优化为往redis里存一条数据
        seckillOrderService.addSeckillOrder(Uid,seckillId,orderNo);

        return orderNo;
    }
//创建订单
    private String createOrderInfo(Long uid, Long seckillId) {
        OrderInfo orderInfo = new OrderInfo();
        SeckillGoodVO vo = seckillGoodService.queryById(seckillId);
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodCount(vo.getGoodStock());
        orderInfo.setGoodImg(vo.getGoodImg());
        orderInfo.setGoodId(vo.getGoodId());
        orderInfo.setGoodPrice(vo.getGoodPrice());
        orderInfo.setUserId(uid);
        orderInfo.setGoodName(vo.getGoodName());
        orderInfo.setSeckillPrice(vo.getSeckillPrice());
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");
        orderInfoMapper.save(orderInfo);
        return orderInfo.getOrderNo();

    }

    @Override
    public OrderInfo queryByorderNo(String orderNo) {

        return  orderInfoMapper.queryByorderNo(orderNo);
    }

    @Override
    public int changeOrderINfoStatus(String orderNo, Integer statusTimeout) {

        return orderInfoMapper.changeOrderINfoStatus(orderNo,statusTimeout);
    }


    @Override
    public void changePayStatus(String orderNo, Integer status) {
        orderInfoMapper.changePayStatus(orderNo,status);
    }
}
